/**
 * 
 */
package org.shark.colortheme.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.shark.colortheme.util.SPHelper;
import org.shark.colortheme.util.ThemeUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

/**
 * 主题管理器，单例模式，负责主题设置并回调所有注册接口.</br> 必须在Android-Application类中初始化</br>
 * 
 * public class ColorThemeApplication extends Application {</br> private static
 * ColorThemeApplication instance = null;</br> private ColorThemeManager
 * colorThemeManager;</br>
 * 
 * 
 * public synchronized static ColorThemeApplication getInstance() {</br> return
 * instance;</br> }</br>
 * 
 * @Override</br> public void onCreate() {</br> super.onCreate();</br> instance
 *                = this;</br> //初始化</br> colorThemeManager =
 *                ColorThemeManager.getInstance();</br>
 *                colorThemeManager.init(this);</br> //初始化主题APK中的RES-ID</br>
 *                //主题APK-RES-ID注册
 *                ThemePackage.setActivityBackgroundResId(R.drawable
 *                .activity_background);</br>
 *                ThemePackage.setThemeNameResId(R.string
 *                .theme_pkg_name_id);</br> }</br> </br>
 * 
 * 
 * 
 * @author hljdrl@gmail.com
 * 
 */
@SuppressLint("HandlerLeak")
public final class ColorThemeManager implements ColorStyleObservable {
	/**
	 * 颜色主题-状态码
	 */
	private static final int STATE_COLOR_STYLE_CHAGE = 1;
	/**
	 * Activity背景图片-状态码
	 */
	private static final int STATE_ACTIVITY_IMAGE_STYLE_CHAGE = 5;
	/**
	 * 颜色主题-颜色配置文件
	 */
	private ColorStyle mColorStyle;
	/**
	 * Activity背景图片-配置文件
	 */
	private ImageStyle mActivityImageStyle;
	/**
	 * 是否保存-Activiyt背景图片-配置文件，保存以后下次会默认读取已经保存的配置
	 */
	private boolean mSaveActivityBackground = Boolean.FALSE;
	/**
	 * 所有主题接口注册容器
	 */
	private List<StyleObserver> mColorStyleObservers = new ArrayList<StyleObserver>();

	private List<ThemePackage> mThemePackages = new ArrayList<ThemePackage>();
	/**
	 * 上下文
	 */
	private Context mContext;
	/**
	 * 标签
	 */
	String TAG = getClass().getSimpleName();
	/**
	 * 主题管理器-实例-单例模式
	 */
	private static ColorThemeManager instance = new ColorThemeManager();

	/**
	 * 获得APK主题包资源配置文件，copy List
	 * 
	 * @return
	 */
	public final List<ThemePackage> getThemePackages() {
		List<ThemePackage> copy = new ArrayList<ThemePackage>(mThemePackages);
		return copy;
	}

	/**
	 * 私有的默认构造子
	 */
	private ColorThemeManager() {

	}

	private AbsImageLoader mAbsImageLoader;

	/**
	 * 初始化方法，会默认加载已经设置的颜色主题、图片主题
	 * 
	 * @param ctx
	 */
	public void init(Context ctx) {
		mContext = ctx;
		mAbsImageLoader = new ImageLoader();
		setColorTheme();
		mThemePackages.addAll(ThemeUtil.loadAllThemePackage(mContext));
	}

	/**
	 * 图片加载器
	 * 
	 * @return
	 */
	public AbsImageLoader getImageLoader() {
		return mAbsImageLoader;
	}

	/**
	 * 初始化方法，会默认加载已经设置的颜色主题、图片主题
	 * 
	 * @param ctx
	 * @param _imageloader
	 *            图片加载器
	 */
	public void init(Context ctx, AbsImageLoader _imageloader) {
		mContext = ctx;
		mAbsImageLoader = _imageloader;
		setColorTheme();
		mThemePackages.addAll(ThemeUtil.loadAllThemePackage(mContext));
	}

	/**
	 * 静态工厂方法
	 */
	public synchronized static ColorThemeManager getInstance() {
		if (instance == null) {
			instance = new ColorThemeManager();
		}
		return instance;
	}

	/**
	 * 加载颜色主题、图片主题 并设置给页面
	 */
	public void setColorTheme() {
		String color = SPHelper.getColor(mContext);
		ColorStyle cache = new ColorStyle();
		cache.setColor(color);
		cache.setColor_normal(color);
		cache.setColor_pressed(ColorHelper.convertToPressed(color));
		setColorStyle(cache);
		//
		ImageStyle imageStyle = new ImageStyle();
		imageStyle.setStyleName(ImageStyle.IMAGE_STYLE_ACTIVITY_BG);
		String imageURI = SPHelper.getActivityBackgroundFile(mContext);

		Uri uri = SPHelper.readActivityBackgroundUri(mContext);
		if (uri != null) {
			imageStyle.setImageURI(uri.toString());
			imageStyle.setType(ImageStyle.TYPE_MEDIA_DB);
			imageStyle.setDrawable(mAbsImageLoader.loadKitKatMediaAsDrawable(
					mContext, uri));
		} else {
			imageStyle.setImageURI(imageURI);
			imageStyle.setType(ImageStyle.TYPE_FILE);
			// 图片内存溢出-注意事项
			// 图片内存溢出-注意事项
			mAbsImageLoader.loadPictureDrawable(imageStyle);
			// 图片内存溢出-注意事项
			// 图片内存溢出-注意事项
		}

		setActivityImageStyle(imageStyle);
	}

	/**
	 * 图片主题配置文件
	 * 
	 * @return
	 */
	public ColorStyle getColorStyle() {
		return mColorStyle;
	}

	/**
	 * Activity背景图片配置文件
	 * 
	 * @return
	 */
	public ImageStyle getActivityImageStyle() {
		return mActivityImageStyle;
	}

	/**
	 * 设置而颜色主题配置文件
	 * 
	 * @param style
	 */
	public void setColorStyle(ColorStyle style) {
		mColorStyle = style;
		Message msg = mHandler.obtainMessage(STATE_COLOR_STYLE_CHAGE);
		mHandler.sendMessage(msg);
	}

	/**
	 * 设置Activity-背景图片配置文件
	 * 
	 * @param style
	 */
	public void setActivityImageStyle(ImageStyle style) {
		mActivityImageStyle = style;
		if (mActivityImageStyle.getDrawable() != null) {
			Message msg = mHandler
					.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
			mHandler.sendMessage(msg);
		}
	}

	/**
	 * 设置Activity-背景图片
	 * 
	 * @param imageFile
	 */
	public void setActivityBackground(File imageFile) {
		if (mActivityImageStyle != null) {
			mActivityImageStyle.setImageURI(imageFile.toString());
			mActivityImageStyle.setType(ImageStyle.TYPE_FILE);
			Message msg = mHandler
					.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
			mHandler.sendMessage(msg);
		}
	}

	/**
	 * 设置Activity-背景图片
	 * 
	 * @param image
	 */
	@SuppressWarnings("deprecation")
	public void setActivityBackground(Bitmap image) {
		if (mActivityImageStyle != null) {
			// mActivityImageStyle.setImageURI(imageFile.toString());
			mActivityImageStyle.setType(ImageStyle.TYPE_BITMAP);
			mActivityImageStyle.setDrawable(new BitmapDrawable(image));
			Message msg = mHandler
					.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
			mHandler.sendMessage(msg);
		}
	}

	/**
	 * 设置Activity-背景图片
	 * 
	 * @param imageFile
	 */
	public void setActivityBackground(String imageFile) {
		if (mActivityImageStyle != null) {
			mActivityImageStyle.setImageURI(imageFile);
			mActivityImageStyle.setType(ImageStyle.TYPE_FILE);
			Message msg = mHandler
					.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
			mHandler.sendMessage(msg);
		}
	}

	/**
	 * 设置Activity-背景图片
	 * 
	 * @param _drawable
	 */
	public void setActivityBackground(Drawable _drawable) {
		if (mActivityImageStyle != null) {
			mActivityImageStyle.setType(ImageStyle.TYPE_BITMAP);
			mActivityImageStyle.setDrawable(_drawable);
			Message msg = mHandler
					.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
			mHandler.sendMessage(msg);
		}
	}

	/**
	 * 设置Activity-背景图片
	 * 
	 * @param _drawable
	 */
	public void setActivityBackgroundAsMedia(Uri uri, boolean save) {
		if (mActivityImageStyle != null) {
			mActivityImageStyle.setType(ImageStyle.TYPE_MEDIA_DB);
			mActivityImageStyle.setImageURI(uri.toString());
			Drawable _drawable = mAbsImageLoader.loadKitKatMediaAsDrawable(
					mContext, uri);
			if (_drawable != null) {
				mActivityImageStyle.setDrawable(_drawable);
				Message msg = mHandler
						.obtainMessage(STATE_ACTIVITY_IMAGE_STYLE_CHAGE);
				mHandler.sendMessage(msg);
			} else {
				Toast.makeText(
						mContext,
						"ColorThemeManager-->setActivityBackgroundAsMedia(...) Uri to Drawable error..",
						Toast.LENGTH_LONG).show();
			}

		}
		if (uri != null && save) {
			SPHelper.saveActivityBackgroundUri(mContext, uri);
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case STATE_COLOR_STYLE_CHAGE:
				notifyChageColorStyle();
				break;
			case STATE_ACTIVITY_IMAGE_STYLE_CHAGE:
				notifyChageImageActivityStyle();
				break;
			case PackageThemeObserver.PACKAGE_THEME_ADD:
				notifyChageThemePackage(PackageThemeObserver.PACKAGE_THEME_ADD,
						(ThemePackage) msg.obj);
				break;
			case PackageThemeObserver.PACKAGE_THEME_REMOVE:
				notifyChageThemePackage(
						PackageThemeObserver.PACKAGE_THEME_REMOVE,
						(ThemePackage) msg.obj);
				break;
			default:
				break;
			}
		};
	};

	final protected void notifyChageImageActivityStyle() {
		for (StyleObserver obs : mColorStyleObservers) {
			if (obs instanceof ImageStyleObserver) {
				((ImageStyleObserver) obs).onChageImageStyle(this,
						mActivityImageStyle);
			}
		}
	}

	final protected void notifyChageColorStyle() {
		for (StyleObserver obs : mColorStyleObservers) {
			if (obs instanceof ColorStyleObserver) {
				((ColorStyleObserver) obs).onChageColorStyle(this, mColorStyle);
			}
		}
	}

	final protected void notifyChageThemePackage(int status,
			final ThemePackage theme) {
		for (StyleObserver obs : mColorStyleObservers) {
			if (obs instanceof PackageThemeObserver) {
				if (status == PackageThemeObserver.PACKAGE_THEME_ADD) {
					((PackageThemeObserver) obs).onInstallPackageTheme(theme);
				} else if (status == PackageThemeObserver.PACKAGE_THEME_REMOVE) {
					((PackageThemeObserver) obs).onUnInstallPackageTheme(theme);
				}
			}
		}
	}

	/*
	 * 注册主题回调接口
	 * 
	 * @see
	 * org.shark.colortheme.core.ColorStyleObservable#addStyleObserver(org.shark
	 * .colortheme.core.StyleObserver)
	 */
	@Override
	final public void addStyleObserver(StyleObserver obs) {
		if (obs != null) {
			mColorStyleObservers.add(obs);
		}
	}

	/*
	 * 注销主题回调接口
	 * 
	 * @see
	 * org.shark.colortheme.core.ColorStyleObservable#deleteStyleObserver(org
	 * .shark.colortheme.core.StyleObserver)
	 */
	@Override
	final public void deleteStyleObserver(StyleObserver obs) {
		if (obs != null) {
			mColorStyleObservers.remove(obs);
		}
	}

	final public void addThemePackage(ThemePackage theme) {
		if (theme != null) {
			if (!mThemePackages.contains(theme)) {
				mThemePackages.add(theme);
				Message msg = mHandler.obtainMessage(
						PackageThemeObserver.PACKAGE_THEME_ADD, theme);
				mHandler.sendMessage(msg);
			}
		}
	}

	final public void deleteThemePackage(ThemePackage theme) {
		if (theme != null) {
			if (mThemePackages.contains(theme)) {
				mThemePackages.remove(theme);
				Message msg = mHandler.obtainMessage(
						PackageThemeObserver.PACKAGE_THEME_REMOVE, theme);
				mHandler.sendMessage(msg);
			}
		}
	}

	/**
	 * 是否保存-Activity设置的背景图片
	 * 
	 * @return
	 */
	final public boolean isSaveActivityBackground() {
		return mSaveActivityBackground;
	}

	/**
	 * 是否保存-Activity设置的背景图片
	 * 
	 * @param mSaveActivityBackground
	 */
	final public void setSaveActivityBackground(boolean mSaveActivityBackground) {
		this.mSaveActivityBackground = mSaveActivityBackground;
	}

	/**
	 * 加载activity的主题背景图片，并设置到activity
	 * 
	 * @param _aty
	 */
	final public void setupActivityBackground(Activity _aty) {
		if (_aty != null && mActivityImageStyle != null) {
			Drawable _drawable = mActivityImageStyle.getDrawable();
			if (_drawable != null) {
				_aty.getWindow().setBackgroundDrawable(_drawable);
				Log.e(TAG, "setupActivityBackground--> _drawable 设置背景成功");
			} else {
				Log.e(TAG, "setupActivityBackground--> _drawable=null 设置背景失败");
			}
		}
	}

	final public void setupActionBar(View _actionbar) {
		if (_actionbar != null) {
			if (mColorStyle != null) {
				_actionbar.setBackgroundColor(Color.parseColor(mColorStyle
						.getColor()));
			}
		}
	}

}
